/*
 * @Author: DUST
 * @Date: 2023-11-25 21:47:07
 * @LastEditors: DUST
 * @LastEditTime: 2023-11-25 23:38:24
 * @FilePath: \business-card-system\server\utils\upload.ts
 * @Description: 
 * undefined
 */

import { Context } from "koa";
import fs from "fs";
import responese from "./responese";
import path from "path";
import MD5 from "./MD5";


const uploadFile = (ctx: Context, isCanBeNull = false) => {
  console.log("开始文件存储~");
  const file = ctx.request.files?.file;
  // console.log("file", file);
  if(file) {
    // @ts-ignore
    const type = file.mimetype;
    //@ts-ignore
    const name = file.originalFilename;
    console.log(file, type, name);
    //@ts-ignore
    const fileStream = fs.createReadStream(file.filepath);
    const ext = path.extname(name);
    const filePath = "/upload/" + createStr() + ext;
    const writeFile = fs.createWriteStream("public" + filePath);
    fileStream.pipe(writeFile);
    return filePath;
  } else if(isCanBeNull) {
    return false;
  } else {
    return responese.errorResponese(ctx, "文件缺失");
  }
}

const createStr =() => {
  const date = Number(new Date());

  return MD5(date.toString());
}

export default uploadFile;